import pandas as pd
import numpy as np
from django.http import HttpResponse
from django.shortcuts import render, redirect
import time
import json
import random
from .module.api import UploadFileForm, handle_uploaded_file
from .module.format_module import fomat_files, get_all_data, get_select_date_list, get_select_double, complie_bp_toarr
import os

file_path = ""


def index(request):
    return redirect("/main")


def main(request):
    print("defaultText")
    this = {"msg": "success", "code": 200, "data": {}}
    this["data"] = "测试数据"
    this["newrandom"] = random.random()
    file_path = "static/file/{}".format("做市商报价2021-05-28.xlsx")
    this = json.loads(json.dumps(this))
    return render(request, "index.html", this)


def select_part(request):
    # request.body
    if request.method == 'POST':
        # pd_data[pd_data["leg_party"].isin(["花旗银行"])]
        print("defaultText")
        # getTime
        slect_title = ""
        # path_join = os.path.join(
        # os.getcwd(), "static/file/{}".format("做市商报价2021-05-28.xlsx"))
        # fomat_files(path_join)
        pd_title_data = get_all_data("leg_party")
        # pd_data[pd_data["leg_party"].isin(["花旗银行"])]
        pd_title_data = pd_title_data[pd_title_data.isin([slect_title])]
        add_date_list = pd_title_data["add_date"].unique()
        # time.mktime(time.strptime(tss2, "%Y-%m-%d %H:%M:%S"))
        print("获取对应的日期内容:", add_date_list)
        return HttpResponse("返回后的内容:")
    this = {"msg": "success", "code": 200, "data": {}}
    this["msg"] = "请正确请求!"
    this["code"] = 302
    this = json.dumps(this)
    return HttpResponse(this)


def backOtherrep():
    print("获取对应的选择内容:")
    this = {"msg": "success", "code": 200, "data": {}}
    this["msg"] = "请正确请求!"
    this["code"] = 302
    this = json.dumps(this)
    return HttpResponse(this)


def backsuccesrep(data, msg="success"):
    print("获取对应的选择内容:")
    this = {"msg": "success", "code": 200, "data": {}}
    this["msg"] = msg
    this["data"] = json.loads(json.dumps(data))
    this = json.dumps(this)
    return HttpResponse(this)


def get_all_counp(request):
    # pd_data["leg_party"].isin(["花旗银行"])
    # 获取所有的对应的数据 然后要全部计算
    print("defaultText")
    return HttpResponse("获取计算后内容:")


def getTableDataList(request):
    print("获取对应的table的内容:")
    if request.method == 'POST':
        value = json.loads(request.body)["select_leg_party"]
        value1 = json.loads(request.body)["select_date"]
        get_select_double(
            [{"keys": "leg_party", "values": value}, {"keys": "add_date", "values": value1}])
        print("获取的选择时间:", value)
        pd_arr = complie_bp_toarr()
        data = {
            "pd_arr": json.loads(json.dumps(pd_arr))
        }
        return backsuccesrep(data)
    return backOtherrep()


def getSelectDateAll(request):
    # get_select_date_list
    if request.method == 'POST':
        value = json.loads(request.body)["selct_party"]
        print("获取对应的内容1:", request.body)
        # leg_party
        print("获取对应的内容2:", value)
        # print("变量内容:", value.encode("gbk").decode("utf-8"))
        # "add_date"
        pd_list = get_select_date_list(value, "add_date")
        print("获取对应的内容1:", pd_list)
        # pd_list[0]
        # print("格式化信息:", time.mktime(
        # time.strptime(str(pd_list[0]), "%Y/%m/%d")))
        # dd=str(vars.split("T")[0])
        pd_list = [str(str(val).split("T")[0]) for val in pd_list]
        print("获取对应的内容2:", pd_list)
        this = {"msg": "success", "code": 200, "data": {}}
        this["data"]["date_list"] = pd_list
        this = json.dumps(this)
        return HttpResponse(this)
    return backOtherrep()


def get_title_list(request):
    if request.method == 'GET':
        print("获取所有的标题:")
        # path_join = os.path.join(
        #     os.getcwd(), "static/file/{}".format("做市商报价2021-05-28.xlsx"))
        # fomat_files(path_join)
        pd_list = get_all_data("leg_party")
        pd_list = list(pd_list)
        this = {"msg": "success", "code": 200, "data": {}}
        this["data"]["title_list"] = json.loads(json.dumps(pd_list))
        this = json.dumps(this)
        return HttpResponse(this)
    this = {"msg": "success", "code": 200, "data": {}}
    this["msg"] = "请正确请求!"
    this["code"] = 302
    this = json.dumps(this)
    return HttpResponse(this)


def postfile(request):
    if request.method == 'POST':
        # print(request.body)
        # return HttpResponse("获取request的内容:")
        print("输出内容后:", request.method, request.FILES)
        form = UploadFileForm(request.POST, request.FILES)
        print("未执行?", request.FILES)
        print(form)
        # print("111")
        # print(request.body)
        # print(request.FILES)
        # print(request.FILES["file"])
        # 做市商报价2021-05-28.xlsx
        # print(dir(request.FILES))
        file = request.FILES.get('file')
        title = request.POST.get('title')
        # title = title
        print("获取的请求数据内容:")
        print(file, title)
        if form.is_valid():
            print("文件写到本地?")
            # title, file
            handle_uploaded_file(request.FILES, title)
            print("文件地址?", os.getcwd())
            path_join = os.path.join(
                os.getcwd(), "static/file/{}".format(title))
            # os.path.dirname()
            flag = fomat_files(path_join)
            # flags = fomat_files(file_path)
            if flag == True:
                this = {"msg": "success", "code": 200, "data": {}}
                this["data"]["files"] = "static/file/{}".format(title)
                file_path = this["data"]["files"]
                this = json.dumps(this)
                return HttpResponse(this)
            else:
                this = {"msg": "", "code": 302, "data": {}}
                # this["data"]["files"] = "/static/file/{}".format(title)
                this["msg"] = "请输入正确文件信息!"
                this = json.dumps(this)
                return HttpResponse(this)
        else:
            this = {"msg": "success", "code": 200, "data": {}}
            this["msg"] = "请上传文件!"
            this["code"] = 302
            this = json.dumps(this)
            return HttpResponse(this)
    this = {"msg": "success", "code": 200, "data": {}}
    this["msg"] = "请正确请求!"
    this["code"] = 302
    this = json.dumps(this)
    return HttpResponse(this)
